package com.ffapp.helper.mservice;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.helper.basis.Constants;
import com.ffapp.helper.util.CountDown;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import my.BleUtils;

public class HeartService extends Service {

    PendingIntent pi;
    AlarmManager manager;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    BleLog.d("HeartService ====");
                    BleUtils.write(HexUtil.chineseWordToGbk("heart"));
                    toSleep(15);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return super.onStartCommand(intent, flags, startId);
    }


    public void toSleep(int time) {
        Log.d("LongRunningService", "执行代码将server注册到下一次启动中");
        manager = (AlarmManager) getSystemService(ALARM_SERVICE);
//        int anHour = 60 * 60 * 1000; // 这是一小时的毫秒数
        int anHour = time * 1000; // 这是一分钟的毫秒数
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent i = new Intent(this, AlarmReceiver.class);
        pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
    }



    @Override
    public void onDestroy() {
        Log.d("LongRunningService", "stop");
        manager.cancel(pi);//关闭的服务的时候同时关闭广播注册者
        super.onDestroy();
    }
}
